package ru.reinvent.perspectiva.activities;

import ru.reinvent.perspectiva.R;
import ru.reinvent.perspectiva.cash.PerspectivaProvider;
import ru.reinvent.perspectiva.fragments.AboutFragment;
import ru.reinvent.perspectiva.fragments.AboutLombardFragment;
import ru.reinvent.perspectiva.fragments.CatalogFragment;
import ru.reinvent.perspectiva.fragments.ContactsFragment;
import ru.reinvent.perspectiva.fragments.OfferFragment;
import ru.reinvent.perspectiva.fragments.OneLotFragment;
import ru.reinvent.perspectiva.net.NetManager;
import ru.reinvent.perspectiva.net.NetManager.LotsDownloadAdapter;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.internal.widget.IcsProgressBar;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends SherlockFragmentActivity 
	{
	
	public static final String DT = "Lombard Perspectiva";
	
	private final String CATALOG_TAG = "catalog_fragment";
	private final String ABOUT_TAG = "about_lombard_fragment";
	private final String OFFER_TAG = "offer_fragment";
	private final String CONTACTS_TAG = "contacts_fragment";
	private final String ONE_LOT_TAG = "one_lot_fragment";
	
	private boolean isTablet;
	private boolean isPortraitMode;
	
	private CatalogFragment catalogFragment;
	private OneLotFragment oneLotFragment;
	private OfferFragment offerFragment;
	private AboutLombardFragment aboutFragment;
	private ContactsFragment contactsFragment;

	private Menu menu;
	private final CatalogFragment.FragmentListener catalogListener = new CatalogFragment.FragmentListener() 
		{
		@Override
		public void interfacePrepared() 
			{
			getSupportActionBar().show();
			findViewById(R.id.splash_group).setVisibility(View.GONE);
			
			if (oneLotFragment!=null && oneLotFragment.getLotId()==-1 && catalogFragment.getAdapter()!=null) 
				{
				oneLotFragment.setLotId(catalogFragment.getAdapter().getItem(0).getId());
				oneLotFragment.refresh();
				}
			}
	
		@Override
		public void listViewItemClicked(int lotId) 
			{
			if (isTablet)
				{
				if (!oneLotFragment.isAdded() && !isPortraitMode)
					{
					getSupportFragmentManager().beginTransaction().replace(
							R.id.tablet_landscape_center,oneLotFragment,ONE_LOT_TAG).commit();
					getSupportActionBar().setDisplayHomeAsUpEnabled(true);
					}
				
				oneLotFragment.setLotId(lotId);
				oneLotFragment.refresh();
				}
			else
				{
				final Intent intent = new Intent(MainActivity.this,OneLotActivity.class);
				intent.putExtra(OneLotActivity.EXTRA_LOT_ID,lotId);
				startActivity(intent);
				}
			}
		};

	@Override
    public void onCreate(Bundle savedInstanceState) 
    	{
        super.onCreate(savedInstanceState);
        getWindow().requestFeature((int) Window.FEATURE_ACTION_BAR);
        getSupportActionBar().hide();

		final Configuration conf = getResources().getConfiguration();
		isTablet = ((conf.screenLayout&Configuration.SCREENLAYOUT_SIZE_MASK)==Configuration.SCREENLAYOUT_SIZE_XLARGE); 
		isPortraitMode = (conf.orientation==Configuration.ORIENTATION_PORTRAIT);

		if (savedInstanceState == null) 
			{
			catalogFragment = new CatalogFragment(catalogListener);
			aboutFragment = new AboutLombardFragment();
			contactsFragment = new ContactsFragment();
			
			if (isTablet)
				{
				oneLotFragment = new OneLotFragment();
				offerFragment = new OfferFragment();
				}
			}

		if (isTablet) initTabletInterface();
		else initHandsetInterface();

		if (PerspectivaProvider.DBUsage.isLotsEmpty(this) || PerspectivaProvider.DBUsage.isVendorsEmpty(this)) initiateFullLoad();
    	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState)
		{
		super.onPostCreate(savedInstanceState);
		
		if (savedInstanceState != null)
			{
			String cfTag = isTablet ? CATALOG_TAG : "android:switcher:"+R.id.main_pager+":1";
			Fragment f = getSupportFragmentManager().findFragmentByTag(cfTag);
			if (f != null) 
				{
				catalogFragment = (CatalogFragment) f;
				catalogFragment.setFragmentListener(catalogListener);
				}
			else catalogFragment = new CatalogFragment(catalogListener);
			
			f = getSupportFragmentManager().findFragmentByTag(ABOUT_TAG);
			if (f != null) aboutFragment = (AboutLombardFragment) f;
			else aboutFragment = new AboutLombardFragment();

			f = getSupportFragmentManager().findFragmentByTag(CONTACTS_TAG);
			if (f != null) contactsFragment = (ContactsFragment) f;
			else contactsFragment = new ContactsFragment();
			
			if (isTablet)
				{
				f = getSupportFragmentManager().findFragmentByTag(ONE_LOT_TAG);
				if (f != null) oneLotFragment = (OneLotFragment) f;
				else oneLotFragment = new OneLotFragment();

				f = getSupportFragmentManager().findFragmentByTag(OFFER_TAG);
				if (f != null) offerFragment = (OfferFragment) f;
				else offerFragment = new OfferFragment();
				}
			}
		}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    	{
    	final MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.main, menu);
        this.menu = menu;
    	
        if (offerFragment!=null && offerFragment.isAdded()) setOfferMenuItemVisible(false);  
        
        final SearchView searchView = (SearchView) menu.getItem(0).getActionView();
        searchView.setOnQueryTextListener(new OnQueryTextListener() 
        	{
			@Override
			public boolean onQueryTextSubmit(String query) { return false; }
			@Override
			public boolean onQueryTextChange(String newText) 
				{
				if (catalogFragment.getAdapter() != null)
					catalogFragment.getAdapter().getFilter().filter(newText);
				
				return false;
				}
			});
        
        return super.onCreateOptionsMenu(menu);
    	}
    
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
		{
		switch (item.getItemId())
			{
			case R.id.menu_refresh: initiateFullLoad(); break;
			case R.id.menu_about: (new AboutFragment(true)).show(getSupportFragmentManager(),null); break;
			case R.id.menu_offer: 
				if (isTablet)
					{
					int cId = isPortraitMode ? R.id.tablet_portrait_left_bottom : R.id.tablet_landscape_center;
					getSupportFragmentManager().beginTransaction().replace(cId,offerFragment,OFFER_TAG).commit();
					getSupportActionBar().setDisplayHomeAsUpEnabled(true);
					setOfferMenuItemVisible(false);
					}
				else startActivity(new Intent(this,OfferActivity.class)); 
				break;
			case android.R.id.home:
				if (isTablet)
					{
					if (isPortraitMode && offerFragment.isAdded())
						{
						getSupportFragmentManager().beginTransaction().replace(
								R.id.tablet_portrait_left_bottom,contactsFragment,CONTACTS_TAG).commit();
						getSupportActionBar().setDisplayHomeAsUpEnabled(false);
						setOfferMenuItemVisible(true);
						}
					else if (!isPortraitMode && offerFragment.isAdded())
						{
						getSupportFragmentManager().beginTransaction().replace(
								R.id.tablet_landscape_center,oneLotFragment,ONE_LOT_TAG).commit();
						getSupportActionBar().setDisplayHomeAsUpEnabled(true);
						setOfferMenuItemVisible(true);
						}
					else if (!isPortraitMode && oneLotFragment.isAdded())
						{
						getSupportFragmentManager().beginTransaction().replace(
								R.id.tablet_landscape_center,contactsFragment,CONTACTS_TAG).commit();
						getSupportActionBar().setDisplayHomeAsUpEnabled(false);
						}
					}
				break;
			}
	
		return super.onOptionsItemSelected(item);
    	} 
	
	@Override
	public void onConfigurationChanged(Configuration newConfig)
		{
		super.onConfigurationChanged(newConfig);
		isPortraitMode = (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT);
		
		if (isTablet) 
			{
			FragmentTransaction removeTransaction = getSupportFragmentManager().beginTransaction();
			if (catalogFragment.isAdded()) removeTransaction.remove(catalogFragment);
			if (oneLotFragment.isAdded()) removeTransaction.remove(oneLotFragment);
			if (offerFragment.isAdded()) removeTransaction.remove(offerFragment);
			if (aboutFragment.isAdded()) removeTransaction.remove(aboutFragment);
			if (contactsFragment.isAdded()) removeTransaction.remove(contactsFragment);
			removeTransaction.commit();
			
			final Runnable mainThreadUIUpdater = new Runnable() 
				{
				@Override
				public void run() 
					{ 
					getSupportActionBar().hide();
					getSupportActionBar().setDisplayHomeAsUpEnabled(false);
					initTabletInterface(); 
					}
				};
			
			new Thread(new Runnable() 
				{
				@Override
				public void run() 
					{
					while (fragmentsRetained())
						{
						synchronized (this)
							{
							try { wait(200); } 
							catch (InterruptedException e) {;}
							}
						}
					
					runOnUiThread(mainThreadUIUpdater);
					}
				}).start();
			}
		}
	
	@Override
	protected void onDestroy()
		{
		super.onDestroy();
		NetManager.get().stopDownloadingLots();
		catalogFragment.stopFillContent();
		}
	
	protected boolean fragmentsRetained()
		{
		return catalogFragment.isAdded() || 
				oneLotFragment.isAdded() ||
				offerFragment.isAdded() ||
				aboutFragment.isAdded() ||
				contactsFragment.isAdded();
		}
	
	protected void setOfferMenuItemVisible(boolean visible)
		{
        for (int i=0; i<menu.size(); i++) 
	    	{
	    	if (menu.getItem(i).getItemId() == R.id.menu_offer) 
				{
	    		menu.getItem(i).setVisible(visible);
	    		menu.getItem(i).setEnabled(visible);
	    		break;
				}
	    	}
		}
	
	protected void initHandsetInterface()
		{
        setContentView(R.layout.main_handset);
        
		final ViewPager pager = (ViewPager) findViewById(R.id.main_pager);
		pager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
		pager.setCurrentItem(1);
		pager.setOnPageChangeListener(new OnPageChangeListener() 
			{
			@Override
			public void onPageScrollStateChanged(int state) {;}
			@Override
			public void onPageScrolled(int oldPage, float positionOffset, int positionPixelOffset) {;}

			@Override
			public void onPageSelected(int newPage) 
				{
				if (menu == null) return;
				
				if (newPage==1)
					{
					menu.getItem(0).setEnabled(true);
					menu.getItem(0).setVisible(true);
					
					menu.getItem(1).setEnabled(true);
					menu.getItem(1).setVisible(true);
					}
				else
					{
					MenuItem searchItem = menu.getItem(0);
					if (searchItem.isActionViewExpanded()) searchItem.collapseActionView();
					searchItem.setEnabled(false);
					searchItem.setVisible(false);
					
					menu.getItem(1).setEnabled(false);
					menu.getItem(1).setVisible(false);
					}
				}
			});
		}
	
	protected void initTabletInterface()
		{
        if (isPortraitMode)
        	{
        	setContentView(R.layout.main_tablet_port);
            
        	getSupportFragmentManager().beginTransaction().
        		add(R.id.tablet_portrait_left_top,catalogFragment,CATALOG_TAG).
        		add(R.id.tablet_portrait_right_top,oneLotFragment,ONE_LOT_TAG).
        		add(R.id.tablet_portrait_left_bottom,contactsFragment,CONTACTS_TAG).
        		add(R.id.tablet_portrait_right_bottom,aboutFragment,ABOUT_TAG).commit();
        	}
        else
        	{
            setContentView(R.layout.main_tablet_land);
            
            getSupportFragmentManager().beginTransaction().
            	add(R.id.tablet_landscape_left,catalogFragment,CATALOG_TAG).
            	add(R.id.tablet_landscape_center,contactsFragment,CONTACTS_TAG).
            	add(R.id.tablet_landscape_right,aboutFragment,ABOUT_TAG).commit();
        	}
		}
	
	protected void initiateFullLoad()
		{
		if (!isOnline())
			{
			Toast.makeText(MainActivity.this,R.string.toast_no_connection,Toast.LENGTH_LONG).show();
			getSupportActionBar().show();
			findViewById(R.id.splash_group).setVisibility(View.GONE);
			return;
			}

		getSupportActionBar().hide();
		findViewById(R.id.splash_group).setVisibility(View.VISIBLE);
		
		final TextView lbl = (TextView) findViewById(R.id.splash_info_text);
		lbl.setText(R.string.splash_start_loading);
		lbl.setVisibility(View.VISIBLE);
		
		final IcsProgressBar pg = (IcsProgressBar) findViewById(R.id.splash_progress_bar);
		pg.setProgress(0);
		pg.setVisibility(View.VISIBLE);
		
		NetManager.get().getLotsContent(new LotsNetAdapter(lbl,pg),200,null,this);
		}
	
	protected boolean isOnline() 
		{
		final ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo nInfo = cm.getActiveNetworkInfo();
		 
		if (nInfo != null && nInfo.isConnected()) return true;
		else return false;
		}
	
	public class SectionsPagerAdapter extends FragmentPagerAdapter 
		{
		public SectionsPagerAdapter(FragmentManager fm) { super(fm); }
		@Override
		public int getCount() { return 3; }
		
		@Override
		public Fragment getItem(int position) 
			{
			switch (position) 
				{
				case 0: return aboutFragment; 
				case 1: return catalogFragment; 
				case 2: return contactsFragment;
				}
			return null;
			}

		@Override
		public CharSequence getPageTitle(int position) 
			{
			switch (position) 
				{
				case 0: return getString(R.string.pager_about_title); 
				case 1: return getString(R.string.pager_catalog_title); 
				case 2: return getString(R.string.pager_contacts_title);
				}
			
			return null;
			}
		}
	
	public class LotsNetAdapter extends LotsDownloadAdapter 
		{
		private TextView lbl;
		private IcsProgressBar pg;
		private String updateProgressStr = getString(R.string.splash_loading);
		
		public LotsNetAdapter(TextView lbl, IcsProgressBar pg)
			{
			this.lbl = lbl;
			this.pg = pg;
			}
		
		@Override
		public void updateProgress(int contentLength, int contentDownloaded) 
			{
			int newProgress = (int) (contentDownloaded*70/contentLength);
			if (pg.getProgress() != newProgress) 
				{
				int downloadProgress = (int) (contentDownloaded*100/contentLength);
				lbl.setText(String.format(updateProgressStr,downloadProgress+"%"));
				pg.setProgress(newProgress);
				}
			}
		
		@Override
		public void downloadFailed() 
			{
			Toast.makeText(MainActivity.this,R.string.toast_loading_fail,Toast.LENGTH_LONG).show();
			getSupportActionBar().show();
			findViewById(R.id.splash_group).setVisibility(View.GONE);
			}
		
		@Override
		public void parseStarted() 
			{
			lbl.setText(R.string.splash_parsing);
			pg.setProgress(70);
			}
		
		@Override
		public void parseFailed() 
			{
			Toast.makeText(MainActivity.this,R.string.toast_parsing_fail,Toast.LENGTH_LONG).show();
			getSupportActionBar().show();
			findViewById(R.id.splash_group).setVisibility(View.GONE);
			}
		
		@Override
		public void saveInDBStarted() 
			{
			lbl.setText(R.string.splash_cashing);
			pg.setProgress(80);
			}
		
		@Override
		public void saveInDBFailed() 
			{
			Toast.makeText(MainActivity.this,R.string.toast_cashing_fail,Toast.LENGTH_LONG).show();
			getSupportActionBar().show();
			findViewById(R.id.splash_group).setVisibility(View.GONE);
			}
		
		@Override
		public void saveInDBFinished(int vendorsAdded, int vendorsRemoved, int lotsAdded, int lotsRemoved) 
			{
			lbl.setText(R.string.splash_preparing_list);
			pg.setProgress(90);
			catalogFragment.startFillContent();
			}
		}
	
	}
